package com.pethospital.servlet;

import com.pethospital.entity.Appointment;
import com.pethospital.entity.PageResult;
import com.pethospital.entity.Pet;
import com.pethospital.entity.User;
import com.pethospital.service.AppointmentService;
import com.pethospital.service.PetService;
import com.pethospital.service.impl.AppointmentServiceImpl;
import com.pethospital.service.impl.PetServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.Date;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 预约控制器
 * Appointment Controller Servlet
 * 
 * @author PetHospital System
 * @version 1.0
 */
public class AppointmentServlet extends HttpServlet {
    
    private AppointmentService appointmentService = new AppointmentServiceImpl();
    private PetService petService = new PetServiceImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 从URL路径获取操作类型
        String pathInfo = request.getPathInfo();
        String action = pathInfo != null ? pathInfo.substring(1) : "";

        // 如果路径中没有操作，尝试从参数中获取
        if (action.isEmpty()) {
            action = request.getParameter("action");
            if (action == null) {
                action = "";
            }
        }
        
        try {
            switch (action) {
                case "list":
                    handleList(request, response);
                    break;
                case "my-appointments":
                    handleMyAppointments(request, response);
                    break;
                case "add":
                    handleAdd(request, response);
                    break;
                case "edit":
                    handleEdit(request, response);
                    break;
                case "update":
                    handleUpdate(request, response);
                    break;
                case "delete":
                    handleDelete(request, response);
                    break;
                case "batchDelete":
                    handleBatchDelete(request, response);
                    break;
                case "updateStatus":
                    handleUpdateStatus(request, response);
                    break;
                case "assignDoctor":
                    handleAssignDoctor(request, response);
                    break;
                case "view":
                    handleView(request, response);
                    break;
                case "confirm":
                    handleConfirm(request, response);
                    break;
                case "cancel":
                    handleCancel(request, response);
                    break;
                case "complete":
                    handleComplete(request, response);
                    break;
                case "getAvailableSlots":
                    handleGetAvailableSlots(request, response);
                    break;
                case "statistics":
                    handleStatistics(request, response);
                    break;
                default:
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "无效的操作");
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "服务器内部错误");
        }
    }
    
    /**
     * 处理预约列表查询（管理员）
     */
    private void handleList(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        // 检查管理员权限
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !"admin".equals(currentUser.getUserType())) {
            response.sendRedirect(request.getContextPath() + "/pages/common/unauthorized.jsp");
            return;
        }
        
        // 获取查询参数
        String petName = request.getParameter("petName");
        String serviceType = request.getParameter("serviceType");
        String status = request.getParameter("status");
        String appointmentDateStr = request.getParameter("appointmentDate");
        
        Date appointmentDate = null;
        if (appointmentDateStr != null && !appointmentDateStr.trim().isEmpty()) {
            try {
                appointmentDate = Date.valueOf(appointmentDateStr);
            } catch (IllegalArgumentException e) {
                // 忽略无效日期
            }
        }
        
        // 获取分页参数
        int currentPage = 1;
        int pageSize = 10;
        
        try {
            String pageStr = request.getParameter("page");
            if (pageStr != null && !pageStr.trim().isEmpty()) {
                currentPage = Integer.parseInt(pageStr);
            }
            
            String sizeStr = request.getParameter("size");
            if (sizeStr != null && !sizeStr.trim().isEmpty()) {
                pageSize = Integer.parseInt(sizeStr);
            }
        } catch (NumberFormatException e) {
            // 使用默认值
        }
        
        // 查询预约列表
        PageResult<Appointment> pageResult = appointmentService.searchAppointments(
            petName, serviceType, status, appointmentDate, null, currentPage, pageSize);
        
        // 设置请求属性
        request.setAttribute("pageResult", pageResult);
        request.setAttribute("petName", petName);
        request.setAttribute("serviceType", serviceType);
        request.setAttribute("status", status);
        request.setAttribute("appointmentDate", appointmentDateStr);
        request.setAttribute("serviceTypes", appointmentService.getAllServiceTypes());
        request.setAttribute("doctors", appointmentService.getAllDoctors());
        
        // 转发到预约列表页面
        request.getRequestDispatcher("/pages/admin/appointment-list.jsp").forward(request, response);
    }
    
    /**
     * 处理我的预约查询（普通用户）
     */
    private void handleMyAppointments(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            response.sendRedirect(request.getContextPath() + "/pages/common/login.jsp");
            return;
        }
        
        // 获取查询参数
        String petName = request.getParameter("petName");
        String serviceType = request.getParameter("serviceType");
        String status = request.getParameter("status");
        String appointmentDateStr = request.getParameter("appointmentDate");
        
        Date appointmentDate = null;
        if (appointmentDateStr != null && !appointmentDateStr.trim().isEmpty()) {
            try {
                appointmentDate = Date.valueOf(appointmentDateStr);
            } catch (IllegalArgumentException e) {
                // 忽略无效日期
            }
        }
        
        // 获取分页参数
        int currentPage = 1;
        int pageSize = 10;
        
        try {
            String pageStr = request.getParameter("page");
            if (pageStr != null && !pageStr.trim().isEmpty()) {
                currentPage = Integer.parseInt(pageStr);
            }
            
            String sizeStr = request.getParameter("size");
            if (sizeStr != null && !sizeStr.trim().isEmpty()) {
                pageSize = Integer.parseInt(sizeStr);
            }
        } catch (NumberFormatException e) {
            // 使用默认值
        }
        
        // 查询用户的预约列表
        PageResult<Appointment> pageResult = appointmentService.searchAppointments(
            petName, serviceType, status, appointmentDate, currentUser.getUserId(), currentPage, pageSize);
        
        // 设置请求属性
        request.setAttribute("pageResult", pageResult);
        request.setAttribute("petName", petName);
        request.setAttribute("serviceType", serviceType);
        request.setAttribute("status", status);
        request.setAttribute("appointmentDate", appointmentDateStr);
        request.setAttribute("serviceTypes", appointmentService.getAllServiceTypes());
        request.setAttribute("myPets", petService.getPetsByOwnerId(currentUser.getUserId()));
        
        // 转发到我的预约页面
        request.getRequestDispatcher("/pages/user/my-appointments.jsp").forward(request, response);
    }
    
    /**
     * 处理添加预约
     */
    private void handleAdd(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            response.sendRedirect(request.getContextPath() + "/pages/common/login.jsp");
            return;
        }

        // GET请求：显示添加页面
        if ("GET".equalsIgnoreCase(request.getMethod())) {
            forwardToAddPage(request, response, currentUser, new Appointment());
            return;
        }

        // POST请求：处理添加操作
        String petIdStr = request.getParameter("petId");
        String appointmentDateStr = request.getParameter("appointmentDate");
        String appointmentTimeStr = request.getParameter("appointmentTime");
        String serviceType = request.getParameter("serviceType");
        String symptoms = request.getParameter("symptoms");
        String doctorName = request.getParameter("doctorName");
        String notes = request.getParameter("notes");
        String ownerIdStr = request.getParameter("ownerId");
        
        // 创建预约对象
        Appointment appointment = new Appointment();
        appointment.setServiceType(serviceType);
        appointment.setSymptoms(symptoms);
        appointment.setDoctorName(doctorName);
        appointment.setNotes(notes);
        
        // 设置宠物ID
        if (petIdStr != null && !petIdStr.trim().isEmpty()) {
            try {
                appointment.setPetId(Integer.parseInt(petIdStr));
            } catch (NumberFormatException e) {
                request.setAttribute("error", "宠物ID格式错误");
                forwardToAddPage(request, response, currentUser, appointment);
                return;
            }
        }
        
        // 设置主人ID
        if ("admin".equals(currentUser.getUserType()) && ownerIdStr != null && !ownerIdStr.trim().isEmpty()) {
            try {
                appointment.setOwnerId(Integer.parseInt(ownerIdStr));
            } catch (NumberFormatException e) {
                appointment.setOwnerId(currentUser.getUserId());
            }
        } else {
            appointment.setOwnerId(currentUser.getUserId());
        }
        
        // 设置预约日期
        if (appointmentDateStr != null && !appointmentDateStr.trim().isEmpty()) {
            try {
                appointment.setAppointmentDate(Date.valueOf(appointmentDateStr));
            } catch (IllegalArgumentException e) {
                request.setAttribute("error", "预约日期格式错误");
                forwardToAddPage(request, response, currentUser, appointment);
                return;
            }
        }
        
        // 设置预约时间
        if (appointmentTimeStr != null && !appointmentTimeStr.trim().isEmpty()) {
            try {
                appointment.setAppointmentTime(Time.valueOf(appointmentTimeStr + ":00"));
            } catch (IllegalArgumentException e) {
                request.setAttribute("error", "预约时间格式错误");
                forwardToAddPage(request, response, currentUser, appointment);
                return;
            }
        }
        
        // 添加预约
        if (appointmentService.addAppointment(appointment)) {
            try {
                String successMsg = URLEncoder.encode("添加成功", "UTF-8");
                String redirectUrl = "admin".equals(currentUser.getUserType()) ?
                    "/appointment/list?success=" + successMsg : "/appointment/my-appointments?success=" + successMsg;
                response.sendRedirect(request.getContextPath() + redirectUrl);
            } catch (Exception e) {
                String redirectUrl = "admin".equals(currentUser.getUserType()) ?
                    "/appointment/list" : "/appointment/my-appointments";
                response.sendRedirect(request.getContextPath() + redirectUrl);
            }
        } else {
            request.setAttribute("error", "添加失败，请检查输入信息或时间是否冲突");
            forwardToAddPage(request, response, currentUser, appointment);
        }
    }
    
    /**
     * 转发到添加页面
     */
    private void forwardToAddPage(HttpServletRequest request, HttpServletResponse response,
                                User currentUser, Appointment appointment) throws ServletException, IOException {
        request.setAttribute("appointment", appointment);
        request.setAttribute("serviceTypes", appointmentService.getAllServiceTypes());
        request.setAttribute("doctors", appointmentService.getAllDoctors());

        if ("admin".equals(currentUser.getUserType())) {
            // 管理员可以看到所有宠物
            request.setAttribute("pets", petService.getAllPets());
            request.setAttribute("serviceTypes", appointmentService.getAllServiceTypes());
            request.getRequestDispatcher("/pages/admin/appointment-add.jsp").forward(request, response);
        } else {
            // 普通用户只能看到自己的宠物
            List<Pet> myPets = petService.getPetsByOwnerId(currentUser.getUserId());

            // 调试信息：打印用户ID和宠物数量
            System.out.println("DEBUG: 当前用户ID: " + currentUser.getUserId());
            System.out.println("DEBUG: 用户名: " + currentUser.getUsername());
            System.out.println("DEBUG: 查询到的宠物数量: " + (myPets != null ? myPets.size() : "null"));
            if (myPets != null && !myPets.isEmpty()) {
                for (Pet pet : myPets) {
                    System.out.println("DEBUG: 宠物详情 - ID: " + pet.getPetId() +
                                     ", 名称: '" + pet.getPetName() + "'" +
                                     ", 类型: '" + pet.getPetType() + "'" +
                                     ", 品种: '" + pet.getBreed() + "'" +
                                     ", 主人ID: " + pet.getOwnerId());

                    // 检查并修复异常的宠物名称
                    if (pet.getPetName() == null || pet.getPetName().trim().isEmpty() ||
                        pet.getPetName().matches("\\d+")) { // 如果名称是纯数字
                        System.out.println("DEBUG: 发现异常宠物名称，尝试修复...");
                        String newName = "宠物" + pet.getPetId(); // 临时名称
                        pet.setPetName(newName);
                        System.out.println("DEBUG: 已临时修复宠物名称为: " + newName);
                    }
                }
            } else {
                System.out.println("DEBUG: 宠物列表为空或null");
            }

            // 如果宠物列表为空或null，创建一个测试宠物
            if (myPets == null || myPets.isEmpty()) {
                System.out.println("DEBUG: 宠物列表为空，创建测试宠物");
                myPets = new java.util.ArrayList<>();
                Pet testPet = new Pet();
                testPet.setPetId(999);
                testPet.setPetName("测试宠物");
                testPet.setPetType("狗");
                testPet.setBreed("测试品种");
                testPet.setOwnerId(currentUser.getUserId());
                myPets.add(testPet);
                System.out.println("DEBUG: 已添加测试宠物");
            }

            System.out.println("DEBUG: 最终设置到request的宠物数量: " + myPets.size());
            for (Pet pet : myPets) {
                System.out.println("DEBUG: 最终宠物 - ID: " + pet.getPetId() + ", 名称: " + pet.getPetName());
            }

            request.setAttribute("myPets", myPets);
            request.setAttribute("serviceTypes", appointmentService.getAllServiceTypes());
            request.getRequestDispatcher("/pages/user/appointment-add.jsp").forward(request, response);
        }
    }

    /**
     * 处理编辑预约页面
     */
    private void handleEdit(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            response.sendRedirect(request.getContextPath() + "/pages/common/login.jsp");
            return;
        }

        String appointmentIdStr = request.getParameter("id");
        if (appointmentIdStr == null || appointmentIdStr.trim().isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "预约ID不能为空");
            return;
        }

        try {
            Integer appointmentId = Integer.parseInt(appointmentIdStr);
            Appointment appointment = appointmentService.getAppointmentById(appointmentId);

            if (appointment == null) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "预约不存在");
                return;
            }

            // 检查权限
            if (!appointmentService.hasPermission(appointmentId, currentUser.getUserId(), "admin".equals(currentUser.getUserType()))) {
                response.sendRedirect(request.getContextPath() + "/pages/common/unauthorized.jsp");
                return;
            }

            request.setAttribute("appointment", appointment);
            request.setAttribute("serviceTypes", appointmentService.getAllServiceTypes());
            request.setAttribute("doctors", appointmentService.getAllDoctors());

            if ("admin".equals(currentUser.getUserType())) {
                request.setAttribute("pets", petService.getAllPets());
                request.getRequestDispatcher("/pages/admin/appointment-edit.jsp").forward(request, response);
            } else {
                request.setAttribute("myPets", petService.getPetsByOwnerId(currentUser.getUserId()));
                request.getRequestDispatcher("/pages/user/appointment-edit.jsp").forward(request, response);
            }

        } catch (NumberFormatException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "预约ID格式错误");
        }
    }

    /**
     * 处理更新预约
     */
    private void handleUpdate(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            response.sendRedirect(request.getContextPath() + "/pages/common/login.jsp");
            return;
        }

        String appointmentIdStr = request.getParameter("appointmentId");
        String petIdStr = request.getParameter("petId");
        String serviceType = request.getParameter("serviceType");
        String appointmentDateStr = request.getParameter("appointmentDate");
        String appointmentTime = request.getParameter("appointmentTime");
        String doctorName = request.getParameter("doctorName");
        String status = request.getParameter("status");
        String notes = request.getParameter("notes");

        if (appointmentIdStr == null || appointmentIdStr.trim().isEmpty() ||
            petIdStr == null || petIdStr.trim().isEmpty() ||
            serviceType == null || serviceType.trim().isEmpty() ||
            appointmentDateStr == null || appointmentDateStr.trim().isEmpty() ||
            appointmentTime == null || appointmentTime.trim().isEmpty() ||
            status == null || status.trim().isEmpty()) {

            request.setAttribute("error", "请填写所有必填字段");
            handleEdit(request, response);
            return;
        }

        try {
            Integer appointmentId = Integer.parseInt(appointmentIdStr);
            Integer petId = Integer.parseInt(petIdStr);

            // 检查权限
            if (!appointmentService.hasPermission(appointmentId, currentUser.getUserId(), "admin".equals(currentUser.getUserType()))) {
                response.sendRedirect(request.getContextPath() + "/pages/common/unauthorized.jsp");
                return;
            }

            // 获取原预约信息
            Appointment appointment = appointmentService.getAppointmentById(appointmentId);
            if (appointment == null) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "预约不存在");
                return;
            }

            // 更新预约信息
            appointment.setPetId(petId);
            appointment.setServiceType(serviceType);
            appointment.setAppointmentDate(java.sql.Date.valueOf(appointmentDateStr));
            appointment.setAppointmentTime(Time.valueOf(appointmentTime + ":00"));
            appointment.setDoctorName(doctorName);
            appointment.setStatus(status);
            appointment.setNotes(notes);

            if (appointmentService.updateAppointment(appointment)) {
                try {
                    String successMsg = URLEncoder.encode("更新成功", "UTF-8");
                    String redirectUrl = "admin".equals(currentUser.getUserType()) ?
                        "/appointment/list?success=" + successMsg : "/appointment/my-appointments?success=" + successMsg;
                    response.sendRedirect(request.getContextPath() + redirectUrl);
                } catch (Exception e) {
                    String redirectUrl = "admin".equals(currentUser.getUserType()) ?
                        "/appointment/list" : "/appointment/my-appointments";
                    response.sendRedirect(request.getContextPath() + redirectUrl);
                }
            } else {
                request.setAttribute("error", "更新失败，请检查输入信息或时间是否冲突");
                handleEdit(request, response);
            }
        } catch (NumberFormatException e) {
            request.setAttribute("error", "ID格式错误");
            handleEdit(request, response);
        } catch (IllegalArgumentException e) {
            request.setAttribute("error", "日期格式错误");
            handleEdit(request, response);
        }
    }

    /**
     * 处理更新预约状态
     */
    private void handleUpdateStatus(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            response.getWriter().write("error");
            return;
        }

        String appointmentIdStr = request.getParameter("id");
        String status = request.getParameter("status");

        if (appointmentIdStr == null || appointmentIdStr.trim().isEmpty() ||
            status == null || status.trim().isEmpty()) {
            response.getWriter().write("error");
            return;
        }

        try {
            Integer appointmentId = Integer.parseInt(appointmentIdStr);

            // 检查权限
            if (!appointmentService.hasPermission(appointmentId, currentUser.getUserId(), "admin".equals(currentUser.getUserType()))) {
                response.getWriter().write("unauthorized");
                return;
            }

            if (appointmentService.updateAppointmentStatus(appointmentId, status)) {
                response.getWriter().write("success");
            } else {
                response.getWriter().write("error");
            }
        } catch (NumberFormatException e) {
            response.getWriter().write("error");
        }
    }

    /**
     * 处理分配医生
     */
    private void handleAssignDoctor(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !"admin".equals(currentUser.getUserType())) {
            response.getWriter().write("unauthorized");
            return;
        }

        String appointmentIdStr = request.getParameter("id");
        String doctorName = request.getParameter("doctorName");

        if (appointmentIdStr == null || appointmentIdStr.trim().isEmpty() ||
            doctorName == null || doctorName.trim().isEmpty()) {
            response.getWriter().write("error");
            return;
        }

        try {
            Integer appointmentId = Integer.parseInt(appointmentIdStr);

            if (appointmentService.assignDoctor(appointmentId, doctorName)) {
                response.getWriter().write("success");
            } else {
                response.getWriter().write("error");
            }
        } catch (NumberFormatException e) {
            response.getWriter().write("error");
        }
    }

    /**
     * 处理确认预约
     */
    private void handleConfirm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !"admin".equals(currentUser.getUserType())) {
            response.getWriter().write("unauthorized");
            return;
        }

        String appointmentIdStr = request.getParameter("id");
        if (appointmentIdStr == null || appointmentIdStr.trim().isEmpty()) {
            response.getWriter().write("error");
            return;
        }

        try {
            Integer appointmentId = Integer.parseInt(appointmentIdStr);

            if (appointmentService.confirmAppointment(appointmentId)) {
                response.getWriter().write("success");
            } else {
                response.getWriter().write("error");
            }
        } catch (NumberFormatException e) {
            response.getWriter().write("error");
        }
    }

    /**
     * 处理取消预约
     */
    private void handleCancel(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            response.getWriter().write("error");
            return;
        }

        String appointmentIdStr = request.getParameter("id");
        String reason = request.getParameter("reason");

        if (appointmentIdStr == null || appointmentIdStr.trim().isEmpty()) {
            response.getWriter().write("error");
            return;
        }

        try {
            Integer appointmentId = Integer.parseInt(appointmentIdStr);

            // 检查权限
            if (!appointmentService.hasPermission(appointmentId, currentUser.getUserId(), "admin".equals(currentUser.getUserType()))) {
                response.getWriter().write("unauthorized");
                return;
            }

            if (appointmentService.cancelAppointment(appointmentId, reason)) {
                response.getWriter().write("success");
            } else {
                response.getWriter().write("error");
            }
        } catch (NumberFormatException e) {
            response.getWriter().write("error");
        }
    }

    /**
     * 处理完成预约
     */
    private void handleComplete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !"admin".equals(currentUser.getUserType())) {
            response.getWriter().write("unauthorized");
            return;
        }

        String appointmentIdStr = request.getParameter("id");
        if (appointmentIdStr == null || appointmentIdStr.trim().isEmpty()) {
            response.getWriter().write("error");
            return;
        }

        try {
            Integer appointmentId = Integer.parseInt(appointmentIdStr);

            if (appointmentService.completeAppointment(appointmentId)) {
                response.getWriter().write("success");
            } else {
                response.getWriter().write("error");
            }
        } catch (NumberFormatException e) {
            response.getWriter().write("error");
        }
    }

    /**
     * 处理删除预约
     */
    private void handleDelete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            response.sendRedirect(request.getContextPath() + "/pages/common/login.jsp");
            return;
        }

        String appointmentIdStr = request.getParameter("id");
        if (appointmentIdStr == null || appointmentIdStr.trim().isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "预约ID不能为空");
            return;
        }

        try {
            Integer appointmentId = Integer.parseInt(appointmentIdStr);

            // 检查权限
            if (!appointmentService.hasPermission(appointmentId, currentUser.getUserId(), "admin".equals(currentUser.getUserType()))) {
                response.sendRedirect(request.getContextPath() + "/pages/common/unauthorized.jsp");
                return;
            }

            if (appointmentService.deleteAppointment(appointmentId)) {
                String redirectUrl = "admin".equals(currentUser.getUserType()) ?
                    "/appointment/list?success=删除成功" : "/appointment/my-appointments?success=删除成功";
                response.sendRedirect(request.getContextPath() + redirectUrl);
            } else {
                String redirectUrl = "admin".equals(currentUser.getUserType()) ?
                    "/appointment/list?error=删除失败" : "/appointment/my-appointments?error=删除失败";
                response.sendRedirect(request.getContextPath() + redirectUrl);
            }
        } catch (NumberFormatException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "预约ID格式错误");
        }
    }

    /**
     * 处理批量删除预约
     */
    private void handleBatchDelete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !"admin".equals(currentUser.getUserType())) {
            response.sendRedirect(request.getContextPath() + "/pages/common/unauthorized.jsp");
            return;
        }

        String[] appointmentIdStrs = request.getParameterValues("appointmentIds");
        if (appointmentIdStrs == null || appointmentIdStrs.length == 0) {
            try {
                String errorMsg = URLEncoder.encode("请选择要删除的预约", "UTF-8");
                response.sendRedirect(request.getContextPath() + "/appointment/list?error=" + errorMsg);
            } catch (Exception e) {
                response.sendRedirect(request.getContextPath() + "/appointment/list");
            }
            return;
        }

        try {
            Integer[] appointmentIds = new Integer[appointmentIdStrs.length];
            for (int i = 0; i < appointmentIdStrs.length; i++) {
                appointmentIds[i] = Integer.parseInt(appointmentIdStrs[i]);
            }

            if (appointmentService.batchDeleteAppointments(appointmentIds)) {
                try {
                    String successMsg = URLEncoder.encode("批量删除成功", "UTF-8");
                    response.sendRedirect(request.getContextPath() + "/appointment/list?success=" + successMsg);
                } catch (Exception e) {
                    response.sendRedirect(request.getContextPath() + "/appointment/list");
                }
            } else {
                try {
                    String errorMsg = URLEncoder.encode("批量删除失败", "UTF-8");
                    response.sendRedirect(request.getContextPath() + "/appointment/list?error=" + errorMsg);
                } catch (Exception e) {
                    response.sendRedirect(request.getContextPath() + "/appointment/list");
                }
            }
        } catch (NumberFormatException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "预约ID格式错误");
        }
    }

    /**
     * 处理查看预约详情
     */
    private void handleView(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            response.sendRedirect(request.getContextPath() + "/pages/common/login.jsp");
            return;
        }

        String appointmentIdStr = request.getParameter("id");
        if (appointmentIdStr == null || appointmentIdStr.trim().isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "预约ID不能为空");
            return;
        }

        try {
            Integer appointmentId = Integer.parseInt(appointmentIdStr);
            Appointment appointment = appointmentService.getAppointmentById(appointmentId);

            if (appointment == null) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "预约不存在");
                return;
            }

            // 检查权限
            if (!appointmentService.hasPermission(appointmentId, currentUser.getUserId(), "admin".equals(currentUser.getUserType()))) {
                response.sendRedirect(request.getContextPath() + "/pages/common/unauthorized.jsp");
                return;
            }

            request.setAttribute("appointment", appointment);

            String forwardUrl = "admin".equals(currentUser.getUserType()) ?
                "/pages/admin/appointment-view.jsp" : "/pages/user/appointment-view.jsp";
            request.getRequestDispatcher(forwardUrl).forward(request, response);

        } catch (NumberFormatException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "预约ID格式错误");
        }
    }

    /**
     * 处理获取可用时间段
     */
    private void handleGetAvailableSlots(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String dateStr = request.getParameter("date");
        if (dateStr == null || dateStr.trim().isEmpty()) {
            response.getWriter().write("[]");
            return;
        }

        try {
            Date appointmentDate = Date.valueOf(dateStr);
            List<String> availableSlots = appointmentService.getAvailableTimeSlots(appointmentDate);

            // 构建JSON响应
            StringBuilder json = new StringBuilder("[");
            for (int i = 0; i < availableSlots.size(); i++) {
                json.append("\"").append(availableSlots.get(i)).append("\"");
                if (i < availableSlots.size() - 1) {
                    json.append(",");
                }
            }
            json.append("]");

            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(json.toString());
        } catch (IllegalArgumentException e) {
            response.getWriter().write("[]");
        }
    }

    /**
     * 处理统计信息
     */
    private void handleStatistics(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !"admin".equals(currentUser.getUserType())) {
            response.sendRedirect(request.getContextPath() + "/pages/common/unauthorized.jsp");
            return;
        }

        // 获取统计数据
        List<Object[]> statusStatistics = appointmentService.getStatusStatistics();
        List<Object[]> serviceTypeStatistics = appointmentService.getServiceTypeStatistics();
        long totalCount = appointmentService.getTotalAppointmentCount();
        List<Appointment> todayAppointments = appointmentService.getTodayAppointments();
        List<Appointment> pendingAppointments = appointmentService.getPendingAppointments();

        request.setAttribute("statusStatistics", statusStatistics);
        request.setAttribute("serviceTypeStatistics", serviceTypeStatistics);
        request.setAttribute("totalCount", totalCount);
        request.setAttribute("todayAppointments", todayAppointments);
        request.setAttribute("pendingAppointments", pendingAppointments);

        request.getRequestDispatcher("/pages/admin/appointment-statistics.jsp").forward(request, response);
    }
}
